package com.ruoyi.api.client.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.api.client.domain.dto.*;
import com.ruoyi.api.client.domain.vo.*;
import com.ruoyi.api.client.service.IClientQbmsService;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.constant.QbmsConstants;
import com.ruoyi.common.core.domain.BaseSelect;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfoT;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.satoken.StpClientUtil;
import com.ruoyi.qbms.domain.*;
import com.ruoyi.qbms.domain.vo.QbmsChapterDataVo;
import com.ruoyi.qbms.domain.vo.QbmsRankVo;
import com.ruoyi.qbms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zouhuu
 * @description 客户端题库模块服务层
 * @date 2022/10/17 22:39:20
 */
@Service
public class ClientQbmsServiceImpl implements IClientQbmsService {

    @Autowired
    private IQbmsCategoryService qbmsCategoryService;

    @Autowired
    private IQbmsChapterService qbmsChapterService;

    @Autowired
    private IQbmsQuestionChoiceService qbmsQuestionChoiceService;

    @Autowired
    private IQbmsRecordAnswerService qbmsRecordAnswerService;

    @Autowired
    private IQbmsRecordFavoriteService qbmsRecordFavoriteService;

    @Autowired
    private IQbmsRecordNoteService qbmsRecordNoteService;

    @Autowired
    private IQbmsRecordFixService qbmsRecordFixService;

    @Autowired
    private IQbmsRecordResolveService qbmsRecordResolveService;

    /**
     * 分类列表
     * @return
     */
    @Override
    public R categoryList() {
        List<BaseSelect> baseSelects = qbmsCategoryService.selectQbmsCategoryOptions(new QbmsCategory());
        return R.ok(baseSelects);
    }

    /**
     * 题库答题数据统计
     * @param categoryId
     * @return
     */
    public R categoryAnswerData(Long categoryId) {
        // 题目数量
        int questionNum = qbmsQuestionChoiceService.selectNums(new QbmsQuestionChoice(categoryId));
        QbmsRecordAnswer answer = new QbmsRecordAnswer();
        answer.setCategoryId(categoryId);
        answer.setStatus(CommonConstants.DATA_STATUS_NORMAL);
        answer.setUid(StpClientUtil.getLoginIdAsLong());
        // 答题数量
        int answerNum = qbmsRecordAnswerService.selectNums(answer);
        // 答题人数
        int answerUserNum = qbmsRecordAnswerService.selectUserNums(answer);
        answer.setAnswerStatus(QbmsConstants.QBMS_QUESTION_ANSWER_STATUS_YES);
        // 正确数量
        int answerYesNum = qbmsRecordAnswerService.selectNums(answer);
        BigDecimal answerRate = BigDecimal.ZERO;
        if (questionNum > 0) {
            answerRate = new BigDecimal(answerNum).divide(new BigDecimal(questionNum), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        }
        return R.ok(new QbmsCategoryAnswerDataVo(questionNum, answerNum, answerYesNum, answerUserNum, answerRate));
    }

    /**
     * 答题排名
     * @param answerRankDto
     * @return
     */
    @Override
    public R answerRank(QbmsAnswerRankDto answerRankDto) {
        QbmsRecordAnswer qbmsRecordAnswer = new QbmsRecordAnswer();
        BeanUtils.copyBeanProp(qbmsRecordAnswer, answerRankDto);
        qbmsRecordAnswer.setStatus(CommonConstants.DATA_STATUS_NORMAL);
        List<QbmsRankVo> qbmsRankVoList = qbmsRecordAnswerService.selectAnswerRankList(qbmsRecordAnswer);
        QbmsMyRankVo myRank = new QbmsMyRankVo("未上榜", 0, qbmsRankVoList);
        List<QbmsRankVo> myRnakList = qbmsRankVoList.stream().filter(answer -> StpClientUtil.getLoginIdAsLong() == answer.getUid()).collect(Collectors.toList());
        if (myRnakList.size() > 0) {
            myRank.setCurNum(myRnakList.get(0).getNum());
            myRank.setCurRank("第" + myRnakList.get(0).getRan() + "名");
        }
        return R.ok(myRank);
    }

    /**
     * 获取章节数据
     * @param categoryId
     * @return
     */
    @Override
    public R chapterData(Long categoryId) {
        long userId = StpClientUtil.getLoginIdAsLong();
        QbmsChapter qbmsChapter = new QbmsChapter();
        qbmsChapter.setCategoryId(categoryId);
        qbmsChapter.setUserId(userId);
        // 查询章节列表
        List<QbmsChapterDataVo> chapterList = qbmsChapterService.clientSelectChapterData(qbmsChapter);

        return R.ok( buildChapterDataVo(chapterList));
    }



    /**
     * 章节题目数据
     * @param chapterId
     * @return
     */
    @Override
    public R questionChapterData(Long chapterId) {
        QbmsQuestionChoice qbmsQuestionChoice = new QbmsQuestionChoice();
        qbmsQuestionChoice.setChapterId(chapterId);
        qbmsQuestionChoice.setUserId(StpClientUtil.getLoginIdAsLong());
        List<QbmsQuestionChoice> qbmsQuestionChoices = qbmsQuestionChoiceService.clientSelectQuestionChapterData(qbmsQuestionChoice);
        List<QbmsQuestionChapterDataVo> questionChapterDataVoList = qbmsQuestionChoices
                .stream()
                .map(item -> new QbmsQuestionChapterDataVo(item.getId(), item.getStatus()))
                .collect(Collectors.toList());
        return R.ok(questionChapterDataVoList);
    }

    /**
     * 获取题目信息
     * @param questionId
     * @return
     */
    @Override
    public R questionInfo(Long questionId) {
        QbmsQuestionChoice originQuestion = qbmsQuestionChoiceService.selectQbmsQuestionChoiceById(questionId);
        // 获取最新一条答题记录
        QbmsRecordAnswer answerRecord = selectLastAnswerRecord(StpClientUtil.getLoginIdAsLong(), originQuestion.getId());
        // 获取题目信息
        QbmsQuestionInfoVo qbmsQuestionInfoVo = buildQuestionInfo(originQuestion, answerRecord, QbmsConstants.QBMS_PRACTICE_MODEL_PRACTICE);
        return R.ok(qbmsQuestionInfoVo);
    }

    /**
     * 查询题目列表信息
     * @param qbmsQuestionDto
     * @return
     */
    @Override
    public TableDataInfoT questionList(QbmsQuestionDto qbmsQuestionDto) {
        // 获取题目数据
        QbmsQuestionChoice questionParams = new QbmsQuestionChoice();
        BeanUtils.copyBeanProp(questionParams, qbmsQuestionDto);
        PageHelper.startPage(qbmsQuestionDto.getPageNum(),1);
        List<QbmsQuestionChoice> questionList = qbmsQuestionChoiceService.clientSelectQbmsQuestionList(questionParams);
        long total = new PageInfo(questionList).getTotal();

        Long questionId = null;
        // 获取题目ID
        if (questionList.size() > 0) {
            questionId = questionList.get(0).getId();
        } else {
            return TableDataInfoT.ERROR("已到最后一页");
        }
        // 原始题目信息
        QbmsQuestionChoice originQuestion = qbmsQuestionChoiceService.selectQbmsQuestionChoiceById(questionId);

        // 获取最新一条答题记录
        QbmsRecordAnswer answerRecord = selectLastAnswerRecord(StpClientUtil.getLoginIdAsLong(), originQuestion.getId());

        // 获取题目信息
        QbmsQuestionInfoVo qbmsQuestionInfoVo = buildQuestionInfo(originQuestion, answerRecord, QbmsConstants.QBMS_PRACTICE_MODEL_PRACTICE);
        return TableDataInfoT.SUCCESS(qbmsQuestionInfoVo, total);
    }

    /**
     * 题目答案检查
     * @param answerDto
     * @return
     */
    @Override
    @RepeatSubmit
    public R questionAnswerCheck(QbmsQuestionAnswerDto answerDto) {
        // 回答问题
        List<QbmsQuestionAnswerIssueDto> answerIssues = answerDto.getIssues();
        // 回答答案Map
        Map<Long, String> answerMap = answerIssues.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getAnswer()));
        // 查询原始题目数据
        QbmsQuestionChoice originQuestion = qbmsQuestionChoiceService.selectQbmsQuestionChoiceById(answerDto.getQuestionId());
        List<QbmsQuestionChoiceIssue> qbmsQuestionChoiceIssueList = originQuestion.getQbmsQuestionChoiceIssueList();
        // 判断回答结果
        boolean flag = true;
        for (QbmsQuestionChoiceIssue issue : qbmsQuestionChoiceIssueList) {
            if (! issue.getAnswer().equals(answerMap.get(issue.getId()))) {
                flag = false;
            }
        }
        // 设置答题记录
        String issueIdStr = answerIssues.stream().map(QbmsQuestionAnswerIssueDto::getId).collect(Collectors.toSet()).toString(); // 题目ID字符串
        String answerJsonStr = JSONUtil.toJsonStr(answerIssues); // 答案JSON字符串
        Integer answerStatus = flag ? QbmsConstants.QBMS_QUESTION_ANSWER_STATUS_YES : QbmsConstants.QBMS_QUESTION_ANSWER_STATUS_ERROR; // 回答状态
        BigDecimal score = (flag ? BigDecimal.ONE : BigDecimal.ZERO); // 分数
        QbmsRecordAnswer recordAnswer = new QbmsRecordAnswer(StpClientUtil.getLoginIdAsLong(), originQuestion.getCategoryId(),
                 originQuestion.getSubjectId(), originQuestion.getChapterId(), originQuestion.getId(), issueIdStr, answerJsonStr, answerStatus, score);
        qbmsRecordAnswerService.insertQbmsRecordAnswer(recordAnswer);
        // 返回答题结果
        return R.ok(buildQuestionInfo(originQuestion, recordAnswer, QbmsConstants.QBMS_PRACTICE_MODEL_PRACTICE));
    }

    /**
     * 题目答案信息
     * @param questionId
     * @return
     */
    @Override
    public R questionAnswerInfo(Long questionId) {
        // 用户ID
        long userId = StpClientUtil.getLoginIdAsLong();
        // 原始问题信息
        QbmsQuestionChoice originQuestion = qbmsQuestionChoiceService.selectQbmsQuestionChoiceById(questionId);
        // 获取回答记录列表
        List<QbmsRecordAnswer> answerRecordList = qbmsRecordAnswerService.selectQbmsRecordAnswerList(new QbmsRecordAnswer(userId, questionId, CommonConstants.DATA_STATUS_NORMAL));
        // 设置最新一条回答记录
        QbmsRecordAnswer answerRecord = null;
        if (answerRecordList.size() > 0) {
            answerRecord = answerRecordList.get(0);

        }
        // 构建题目信息
        QbmsQuestionInfoVo qbmsQuestionInfoVo = buildQuestionInfo(originQuestion, answerRecord, QbmsConstants.QBMS_PRACTICE_MODEL_ANSWER);

        return R.ok(qbmsQuestionInfoVo);
    }

    /**
     * 题目收藏
     * @param questionId
     * @return
     */
    @Override
    public R questionFavorite(Long questionId) {

        long uid = StpClientUtil.getLoginIdAsLong();
        QbmsRecordFavorite favorite = new QbmsRecordFavorite();
        favorite.setQuestionId(questionId);
        favorite.setUid(uid);
        List<QbmsRecordFavorite> qbmsRecordFavorites = qbmsRecordFavoriteService.selectQbmsRecordFavoriteList(favorite);
        if (qbmsRecordFavorites.size() > 0) { // 如果存在则取消收藏
            qbmsRecordFavoriteService.deleteQbmsRecordFavoriteById(qbmsRecordFavorites.get(0).getId());
            return R.ok(false, "取消成功");
        } else {
            QbmsQuestionChoice question = qbmsQuestionChoiceService.selectSimpleQuestionById(questionId);
            favorite.setCategoryId(question.getCategoryId());
            favorite.setChapterId(question.getChapterId());
            favorite.setSubjectId(question.getSubjectId());
            qbmsRecordFavoriteService.insertQbmsRecordFavorite(favorite);
            return R.ok(true, "收藏成功");
        }
    }

    /**
     * 题目收藏记录
     * @param questionId
     * @return
     */
    @Override
    public R questionFavoriteRecord(Long questionId) {
        QbmsRecordFavorite favorite = new QbmsRecordFavorite();
        favorite.setQuestionId(questionId);
        favorite.setUid(StpClientUtil.getLoginIdAsLong());
        List<QbmsRecordFavorite> qbmsRecordFavorites = qbmsRecordFavoriteService.selectQbmsRecordFavoriteList(favorite);
        boolean flag = qbmsRecordFavorites.size() > 0 ? true : false;
        return R.ok(flag);
    }

    /**
     * 题目收藏列表
     * @param categoryId
     * @return
     */
    @Override
    public R questionFavoriteList(Long categoryId) {
        QbmsRecordFavorite favoriteParamas = new QbmsRecordFavorite();
        favoriteParamas.setUid(StpClientUtil.getLoginIdAsLong());
        favoriteParamas.setCategoryId(categoryId);
        List<QbmsRecordFavorite> favoriteList = qbmsRecordFavoriteService.selectQbmsRecordFavoriteList(favoriteParamas);
        List<QbmsQuestionFavoriteVo> favoriteVoList = new ArrayList<>();
        if (favoriteList.size() == 0) {
            return R.ok(favoriteVoList);
        }
        // 查询题目列表
        Set<Long> questionIds = favoriteList.stream().map(favorite -> favorite.getQuestionId()).collect(Collectors.toSet());
        List<QbmsQuestionChoice> questionList = qbmsQuestionChoiceService.selectQbmsQuestionByIds(questionIds);
        Map<Long, QbmsQuestionChoice> questionMap = questionList.stream().collect(Collectors.toMap(QbmsQuestionChoice::getId, QbmsQuestionChoice -> QbmsQuestionChoice));

        // 构建笔记视图对象
        favoriteVoList = favoriteList.stream().map(item -> {
            QbmsQuestionFavoriteVo favoriteVo = new QbmsQuestionFavoriteVo();
            BeanUtils.copyBeanProp(favoriteVo, questionMap.get(item.getQuestionId()));
            BeanUtils.copyBeanProp(favoriteVo, item);
            return favoriteVo;
        }).collect(Collectors.toList());

        return R.ok(favoriteVoList);
    }

    /**
     * 题目笔记
     * @param qbmsRecordNoteDto
     * @return
     */
    @Override
    public R questionNoteSave(QbmsRecordNoteDto qbmsRecordNoteDto) {
        QbmsRecordNote qbmsRecordNote = new QbmsRecordNote();
        BeanUtils.copyBeanProp(qbmsRecordNote, qbmsRecordNoteDto);
        if (StringUtils.isNotNull(qbmsRecordNote.getId())) {
            qbmsRecordNoteService.updateQbmsRecordNote(qbmsRecordNote);
            return R.ok("修改成功");
        } else {
            QbmsQuestionChoice question = qbmsQuestionChoiceService.selectSimpleQuestionById(qbmsRecordNote.getQuestionId());
            qbmsRecordNote.setCategoryId(question.getCategoryId());
            qbmsRecordNote.setChapterId(question.getChapterId());
            qbmsRecordNote.setSubjectId(question.getSubjectId());
            qbmsRecordNote.setUid(StpClientUtil.getLoginIdAsLong());
            qbmsRecordNoteService.insertQbmsRecordNote(qbmsRecordNote);
            return R.ok("新增成功");
        }

    }

    /**
     * 题目笔记内容
     * @param questionId
     * @return
     */
    @Override
    public R questionNoteContent(Long questionId) {
        QbmsRecordNote qbmsRecordNote = new QbmsRecordNote();
        qbmsRecordNote.setQuestionId(questionId);

        List<QbmsRecordNote> qbmsRecordNotes = qbmsRecordNoteService.selectQbmsRecordNoteList(qbmsRecordNote);
        long uid = StpClientUtil.getLoginIdAsLong();
        List<QbmsQuestionNoteVo> noteVoList = qbmsRecordNotes.stream().map(item -> {
            QbmsQuestionNoteVo noteVo = new QbmsQuestionNoteVo();
            BeanUtils.copyBeanProp(noteVo, item);
            if (item.getUid().equals(uid)) {
                noteVo.setEditStatus(true);
            }
            return noteVo;
        }).collect(Collectors.toList());
        return R.ok(noteVoList);
    }

    /**
     * 题目笔记列表
     * @param categoryId
     * @return
     */
    @Override
    public R questionNoteList(Long categoryId) {
        QbmsRecordNote qbmsRecordNote = new QbmsRecordNote();
        qbmsRecordNote.setCategoryId(categoryId);
        qbmsRecordNote.setUid(StpClientUtil.getLoginIdAsLong());
        // 查询笔记列表
        List<QbmsRecordNote> noteList = qbmsRecordNoteService.selectQbmsRecordNoteList(qbmsRecordNote);
        List<QbmsQuestionNoteVo> noteVoList = new ArrayList<>();
        if (noteList.size() == 0) {
            return R.ok(noteVoList);
        }
        // 查询题目列表
        Set<Long> questionIds = noteList.stream().map(note -> note.getQuestionId()).collect(Collectors.toSet());
        List<QbmsQuestionChoice> questionList = qbmsQuestionChoiceService.selectQbmsQuestionByIds(questionIds);
        Map<Long, QbmsQuestionChoice> questionMap = questionList.stream().collect(Collectors.toMap(QbmsQuestionChoice::getId, QbmsQuestionChoice -> QbmsQuestionChoice));

        // 构建笔记视图对象
        noteVoList = noteList.stream().map(note -> {
            QbmsQuestionNoteVo noteVo = new QbmsQuestionNoteVo();
            BeanUtils.copyBeanProp(noteVo, questionMap.get(note.getQuestionId()));
            BeanUtils.copyBeanProp(noteVo, note);
            return noteVo;
        }).collect(Collectors.toList());
        return R.ok(noteVoList);
    }

    /**
     * 题库导航数据
     * @param categoryId
     * @return
     */
    @Override
    public R navData(Long categoryId) {
        long uid = StpClientUtil.getLoginIdAsLong();
        int noteNUm = qbmsRecordNoteService.selectNums(new QbmsRecordNote(uid, categoryId));
        int favoriteNum = qbmsRecordFavoriteService.selectNums(new QbmsRecordFavorite(uid, categoryId));
        QbmsRecordAnswer qbmsRecordAnswer = new QbmsRecordAnswer();
        qbmsRecordAnswer.setUid(uid);
        qbmsRecordAnswer.setCategoryId(categoryId);
        qbmsRecordAnswer.setStatus(CommonConstants.DATA_STATUS_NORMAL);
        int answerNum = qbmsRecordAnswerService.selectNums(qbmsRecordAnswer);
        qbmsRecordAnswer.setAnswerStatus(QbmsConstants.QBMS_QUESTION_ANSWER_STATUS_ERROR);
        int mistakeNum = qbmsRecordAnswerService.selectNums(qbmsRecordAnswer);
        return R.ok(new QbmsNavDataVo(noteNUm, favoriteNum, mistakeNum, answerNum));
    }

    /**
     * 题目纠错
     * @param qbmsRecordFixDto
     * @return
     */
    @Override
    public R questionFixSave(QbmsRecordFixDto qbmsRecordFixDto) {
        QbmsRecordFix recordFix = new QbmsRecordFix();
        BeanUtils.copyBeanProp(recordFix, qbmsRecordFixDto);
        if (StringUtils.isNotNull(recordFix.getId())) {
            qbmsRecordFixService.updateQbmsRecordFix(recordFix);
            return R.ok("修改成功");
        } else {
            QbmsQuestionChoice question = qbmsQuestionChoiceService.selectSimpleQuestionById(recordFix.getQuestionId());
            recordFix.setCategoryId(question.getCategoryId());
            recordFix.setChapterId(question.getChapterId());
            recordFix.setSubjectId(question.getSubjectId());
            recordFix.setUid(StpClientUtil.getLoginIdAsLong());
            qbmsRecordFixService.insertQbmsRecordFix(recordFix);
            return R.ok("提交成功，等待审核");
        }
    }

    /**
     * 题目解析保存
     * @param qbmsRecordResolveDto
     * @return
     */
    @Override
    public R questionResolveSave(QbmsRecordResolveDto qbmsRecordResolveDto) {
        QbmsRecordResolve recordResolve = new QbmsRecordResolve();
        BeanUtils.copyBeanProp(recordResolve, qbmsRecordResolveDto);
        QbmsQuestionChoice question = qbmsQuestionChoiceService.selectSimpleQuestionById(recordResolve.getQuestionId());
        recordResolve.setCategoryId(question.getCategoryId());
        recordResolve.setChapterId(question.getChapterId());
        recordResolve.setSubjectId(question.getSubjectId());
        recordResolve.setUid(StpClientUtil.getLoginIdAsLong());
        qbmsRecordResolveService.insertQbmsRecordResolve(recordResolve);
        return R.ok("提交成功，等待审核");
    }

    /**
     * 问题错误列表
     * @param categoryId
     * @return
     */
    @Override
    public R questionMistakeList(Long categoryId) {

        QbmsRecordAnswer answerParams = new QbmsRecordAnswer();
        answerParams.setUid(StpClientUtil.getLoginIdAsLong());
        answerParams.setCategoryId(categoryId);
        answerParams.setAnswerStatus(QbmsConstants.QBMS_QUESTION_ANSWER_STATUS_ERROR);
        answerParams.setStatus(CommonConstants.DATA_STATUS_NORMAL);
        List<QbmsRecordAnswer> answerList = qbmsRecordAnswerService.selectQbmsRecordAnswerList(answerParams);
        List<QbmsQuestionMistakeVo> answerVoList = new ArrayList<>();
        if (answerList.size() == 0) {
            return R.ok(answerVoList);
        }
        Set<Long> questionId = answerList.stream().map(item -> item.getQuestionId()).collect(Collectors.toSet());
        Map<Long, QbmsQuestionChoice> questionMap = qbmsQuestionChoiceService.selectQbmsQuestionByIds(questionId).stream().collect(Collectors.toMap(QbmsQuestionChoice::getId, p -> p));

        // 构建答题视图对象
        answerVoList = answerList.stream().map(note -> {
            QbmsQuestionMistakeVo answerVo = new QbmsQuestionMistakeVo();
            BeanUtils.copyBeanProp(answerVo, questionMap.get(note.getQuestionId()));
            BeanUtils.copyBeanProp(answerVo, note);
            return answerVo;
        }).collect(Collectors.toList());

        return R.ok(answerVoList);
    }

    /**
     * 题目答题列表
     * @param categoryId
     * @return
     */
    @Override
    public R questionAnswerList(Long categoryId) {
        QbmsRecordAnswer answerParams = new QbmsRecordAnswer();
        answerParams.setUid(StpClientUtil.getLoginIdAsLong());
        answerParams.setCategoryId(categoryId);
        answerParams.setStatus(CommonConstants.DATA_STATUS_NORMAL);
        List<QbmsRecordAnswer> answerList = qbmsRecordAnswerService.selectQbmsRecordAnswerList(answerParams);
        List<QbmsQuestionMistakeVo> answerVoList = new ArrayList<>();
        if (answerList.size() == 0) {
            return R.ok(answerVoList);
        }
        Set<Long> questionId = answerList.stream().map(item -> item.getQuestionId()).collect(Collectors.toSet());
        Map<Long, QbmsQuestionChoice> questionMap = qbmsQuestionChoiceService.selectQbmsQuestionByIds(questionId).stream().collect(Collectors.toMap(QbmsQuestionChoice::getId, p -> p));

        // 构建答题视图对象
        answerVoList = answerList.stream().map(note -> {
            QbmsQuestionMistakeVo answerVo = new QbmsQuestionMistakeVo();
            BeanUtils.copyBeanProp(answerVo, questionMap.get(note.getQuestionId()));
            BeanUtils.copyBeanProp(answerVo, note);
            return answerVo;
        }).collect(Collectors.toList());

        return R.ok(answerVoList);
    }


    /**
     * 章节题目重做
     * @param chapterId
     * @return
     */
    @Override
    public R questionAnswerRenewal(Long chapterId) {
        QbmsRecordAnswer answer = new QbmsRecordAnswer();
        answer.setChapterId(chapterId);
        answer.setUid(StpClientUtil.getLoginIdAsLong());
        qbmsRecordAnswerService.batchUpdateStatus(answer);
        return R.ok("重置成功");
    }

    /**
     * 构建章节列表数据视图
     * @param chapterList
     */
    public List<QbmsSubjectChapterDataVo> buildChapterDataVo(List<QbmsChapterDataVo> chapterList) {
        // 按学科分组
        Map<String, List<QbmsChapterDataVo>> subjectMap = chapterList.stream().collect(Collectors.groupingBy(QbmsChapterDataVo::getSubjectName));

        ArrayList<QbmsSubjectChapterDataVo> chapterDataList = new ArrayList<>();
        // 遍历学科
        subjectMap.forEach((subjecName, subjectChapterList) -> {
            // 转换数据
            List<QbmsSubjectChapterDataVo> chapterChild = subjectChapterList.stream().map(item -> {
                BigDecimal chapterRate = BigDecimal.ZERO;
                if (item.getNum() > 0) {
                    BigDecimal chapterNum = new BigDecimal(item.getNum());
                    BigDecimal chapterTotal = new BigDecimal(item.getTotal());
                    chapterRate = chapterNum.divide(chapterTotal, 2,  RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100l));
                }
                return new QbmsSubjectChapterDataVo(item.getId(), item.getName(), item.getTotal(), item.getNum(), chapterRate, null);
            }).collect(Collectors.toList());
            int total = chapterChild.stream().mapToInt(QbmsSubjectChapterDataVo::getTotal).sum();
            int num = chapterChild.stream().mapToInt(QbmsSubjectChapterDataVo::getNum).sum();
            BigDecimal subjectRate = BigDecimal.ZERO;
            if (num > 0) {
                subjectRate = new BigDecimal(num).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100l));
            }
            chapterDataList.add(new QbmsSubjectChapterDataVo(0L, subjecName, total, num, subjectRate, chapterChild));
        });
        return chapterDataList;
    }

    /**
     * 构建问题详细信息
     * @param originQuestion 原始问题
     * @param answerRecord 回答记录
     */
    public QbmsQuestionInfoVo buildQuestionInfo(QbmsQuestionChoice originQuestion, QbmsRecordAnswer answerRecord, String praticeModel) {
        // 构建题目回答信息
        QbmsQuestionInfoVo qbmsQuestionInfoVo = new QbmsQuestionInfoVo();

        // 原始题题目列表
        List<QbmsQuestionChoiceIssue> originIssueList = originQuestion.getQbmsQuestionChoiceIssueList();
        Map<Long, Set<Integer>> answerMap = null;
        if (StringUtils.isNotNull(answerRecord)) {
            String answerstr = answerRecord.getAnswer();
            // 构建回答Map
            answerMap = JSONUtil.toList(answerstr, QbmsQuestionAnswerIssueDto.class)
                    .stream().collect(Collectors.toMap(p -> p.getId(),p -> buildAnswerSetByStr(p.getAnswer(), ",")));
        }

        BeanUtils.copyBeanProp(qbmsQuestionInfoVo, originQuestion);
        Map<Long, Set<Integer>> finalAnswerMap = answerMap;
        List<QbmsQuestionInfoVo.Issue> issueList = originIssueList.stream().map(issue -> {
            // 构建选项列表
            List<QbmsQuestionInfoVo.IssueOption> optionList = Arrays.asList(issue.getIssueOptions().split("===="))
                    .stream()
                    .map(option -> new QbmsQuestionInfoVo.IssueOption(option, false, QbmsConstants.QBMS_ISSUE_OPTION_STATUS_DEFAULT)).collect(Collectors.toList());
            String originAnswer = "";
            String orginAnswerExplain = "";
            // 背题模式 和 已作答情况下 显示答案
            if (QbmsConstants.QBMS_PRACTICE_MODEL_RACITE.equals(praticeModel) || StringUtils.isNotNull(finalAnswerMap)) {
                // 构建答案选项
                Set<Integer> originAnswerSet = buildAnswerSetByStr(issue.getAnswer(), ",");
                for (Integer answer : originAnswerSet) {
                    optionList.get(answer - 1).setChecked(true);
                    optionList.get(answer - 1).setStatus(QbmsConstants.QBMS_ISSUE_OPTION_STATUS_TRUE_NO);
                }
                originAnswer = convertAnswerSetToCharStr(originAnswerSet);
                orginAnswerExplain = issue.getAnswerExplain();
                qbmsQuestionInfoVo.setAnswerFlag(true);
            }
            String myanswer = "";
            // 构建回答状态
            if (StringUtils.isNotNull(finalAnswerMap)) {
                Set<Integer> answerSet = finalAnswerMap.get(issue.getId());
                if (StringUtils.isNotNull(answerSet)) {
                    for (Integer answer : answerSet) {
                        QbmsQuestionInfoVo.IssueOption tempOption = optionList.get(answer - 1);
                        if (tempOption.getChecked()) {
                            tempOption.setStatus(QbmsConstants.QBMS_ISSUE_OPTION_STATUS_TRUE_YES);
                        } else {
                            tempOption.setChecked(true);
                            tempOption.setStatus(QbmsConstants.QBMS_ISSUE_OPTION_STATUS_FALSE_YES);
                        }
                    }
                }
                myanswer = convertAnswerSetToCharStr(answerSet);
            }

            return new QbmsQuestionInfoVo.Issue(issue.getId(), issue.getIssue(), optionList, originAnswer, orginAnswerExplain, myanswer);
        }).collect(Collectors.toList());
        qbmsQuestionInfoVo.setIssues(issueList);
        return qbmsQuestionInfoVo;
    }


    /**
     * 根据答案字符串构建答案Set集合
     * @param answerstr 答案字符串
     * @param splitstr 分割符
     */
    public Set<Integer> buildAnswerSetByStr(String answerstr, String splitstr) {
        return Arrays.stream(answerstr.split(splitstr)).map(str -> Integer.parseInt(str)).collect(Collectors.toSet());
    }

    /**
     * 查询最近做题记录
     * @param userId
     * @param questionId
     * @return
     */
    public QbmsRecordAnswer selectLastAnswerRecord(Long userId, Long questionId) {
        // 获取回答记录列表
        List<QbmsRecordAnswer> answerRecordList = qbmsRecordAnswerService.selectQbmsRecordAnswerList(new QbmsRecordAnswer(userId, questionId, CommonConstants.DATA_STATUS_NORMAL));
        // 设置最新一条回答记录
        QbmsRecordAnswer answerRecord = null;
        if (answerRecordList.size() > 0) {
            answerRecord = answerRecordList.get(0);
        }
        return answerRecord;
    }

    /** 转换答案 */
    public String convertAnswerSetToCharStr(Set<Integer> answerSet) {
        String str = "";
        for (Integer c : answerSet) {
            char num = (char) (c + 64);
            str += num;
        }
        return str;
    }
}
